import { makeAutoObservable } from "mobx";
import { axios_request } from '@/utils/axios_request'
import qs from 'qs';
import moment from 'moment';


const getRandomuserParams = (params) => ({
    pagesize: params ? params.pageSize : 10,
    page: params ? params.current - 1 : 0,
    ...params,
});


export default class OperateStore{
    constructor(){
        makeAutoObservable(this)
    }

    createItem = async(api, data) => {
        if(data.create_time){
            data.create_time = data.create_time.format("YYYY-MM-DD HH:mm:ss")
        }
        if(data.update_time){
            data.update_time = data.update_time.format("YYYY-MM-DD HH:mm:ss")
        }
        if(data.birthday){
            data.birthday = data.birthday.format("YYYY-MM-DD")
        }
        const res = await axios_request.post(api, data)
        return res
    }

    modifyItem = async(api, id, data) => {
        if(data.create_time){
            data.create_time = data.create_time.format("YYYY-MM-DD HH:mm:ss")
        }
        if(data.update_time){
            data.update_time = data.update_time.format("YYYY-MM-DD HH:mm:ss")
        }
        if(data.birthday){
            data.birthday = data.birthday.format("YYYY-MM-DD")
        }
        const res = await axios_request.put(`${api}/${id}`, data)
        return res
    }

    deleteItem = async(api, id) => {
       const res = await axios_request.delete(`${api}/${id}`)
       return res
    }

    getItems = async(api, params) => {
        const res = await axios_request.get(`${api}?${qs.stringify(getRandomuserParams(params))}`)
        return res.data
    }

    getItem = async(api, id) => {
        const res = await axios_request.get(`${api}/${id}`)
        if(res.data.create_time){
            res.data.create_time = moment(res.data.create_time)
        }
        if(res.data.update_time){
            res.data.update_time = moment(res.data.update_time)
        }
        if(res.data.birthday){
            res.data.birthday = moment(res.data.birthday)
        }
        return res.data
    }

    getDetails = async(api, id) => {
        const res = await axios_request.get(`${api}/${id}`)
        return res.data
    }
}